from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect, reverse
from crm import models


class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):
        url = request.path_info
        if url in [reverse('crm:login'), reverse('crm:reg')]:
            return
        if url.startswith('/admin'):
            return
        if request.session.get('is_login') != '1':
            return redirect('crm:login')
        user_obj = models.UserProfile.objects.filter(pk=request.session.get('pk')).first()
        request.user_obj = user_obj
